<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:充值提现接口
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\Api;
use app\api\model\UserCashRar as cashModel;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate;
use support\Request;
use support\Response;
use app\ApiController;
use PayPal\Paypal;


class CashController extends ApiController
{
    protected $noNeedLogin = ['index', 'payForRecharge', 'paypalNotify', 'paypalCallBack','getOptions'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 充值提现列表
     * @param  [type] $token [登录token]
     * @return [type]        [json数据]
     */
    public function index($token)
    {
        $u_id = $this->auth->u_id;
        //支付状态
        $tmp              = cashModel::getPayFlag();
        $pay_flag_options = output_select($tmp, []);
        //审核状态
        $tmp                = cashModel::getCheckFlag();
        $check_flag_options = output_select($tmp, []);
        //过帐类型
        $tmp          = cashModel::getType();
        $type_options = output_select($tmp, []);
        $request      = request();
        $limit        = $request->get('limit', 10);
        $w[]          = ['a.u_id', '=', $u_id];

        if ($request->get('remark')) {
            $w[] = ['a.remark', 'like', '%' . $request->get('remark') . '%'];

        }
        if ($request->get('pay_flag')) {
            $w[] = ['a.pay_flag', '=', $request->get('pay_flag')];

        }

        if ($request->get('check_flag')) {
            $w[] = ['a.check_flag', '=', $request->get('check_flag')];

        }
        if ($request->get('type')) {
            $w[] = ['a.type', '=', $request->get('type')];

        }

        $q = cashModel::alias('a')->where($w);
        $q->order("a.id","desc");
        $ls = $q->paginate(['list_rows' => $limit, 'request' => $request->all()]);

        $res        = $ls->items();
        $pay_flag   = cashModel::getPayFlag();
        $check_flag = cashModel::getCheckFlag();
        $type       = cashModel::getType();

        $res = array_map(function ($v) use ($pay_flag, $check_flag, $type) {
            $v->pay_flag_txt   = $pay_flag[$v->pay_flag];
            $v->type_txt       = $type[$v->type];
            $v->check_flag_txt = $check_flag[$v->check_flag];
            $v->user_info      = $v->user_info;
            $v->profile        = $v->user_info->profile;
            return $v;
        }, $res);

        $data['ls']      = $res;
        $data['total']   = $ls->total();
       

        return $this->success(__('Operation successful'), $data);
    }

    /**
     * 充值
     */
    public function recharge()
    {

        $data['money'] = 1;
        $post          = request()->post();

        $data     = ['cash' => $post['cash'], 'description' => __('Recharge'), 'u_id' => $this->auth->u_id,'from'=>$post['from']];
        $data     = authcode(json_encode($data), 'ENCODE');
        
        $pay_link = "/api/Cash/payForRecharge?".http_build_query(['pm' => $data]);

        return $this->success(__('Operation successful'), ['pay_link' => $pay_link]);

    }

    /**
     * 启动paypal支付
     * @param  [type] $pm [description]
     * @return [type]     [description]
     */
    public function payForRecharge(Request $request)
    {
        try {
            $pm  = $request->get("pm");
            $str = authcode($pm, 'DECODE');
            $pm  = json_decode($str, true);
  
            $validate = new \app\api\validate\UserCashRar;
          
            $result   = $validate->check($pm);
           
            if (!$result) {
                return $this->error($validate->getError());
            } else {

                $instance = new Paypal;

                $cfg           = getConfig("mission");
                $model         = new \app\api\model\UserCashRar;
                $post['type']  = 1;
                $post['u_id']  = $pm['u_id'];
                $post['cash']  = $pm['cash'];
                $post['money'] = $pm['cash'] * $cfg['money_to_cash'];
                $post['from']  = $pm['from'];
                $data          = $model->save($post);
                $send_data     = [
                    'rar_id'  => $model->id,
                    'product' => $model->id,
                    'price'   => $pm['cash'],
                ];

                $url =  $instance->createForm($send_data);
              
                return redirect($url);
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }

    }

    /* 启动paypal支付
     * @param  [type] $pm [description]
     * @return [type]     [description]
     */
    public function paypalCallBack()
    {

        $instance = new Paypal;
        $r = $instance->Callback($this->request->get());    

        $from = (int)Db::name("user_cash_rar")->where('follow_no',$this->request->get('follow_no'))->value('from');
        
        $jumps = [
            0=> '/index/User/moneylog.html',
            1=> '/index/User/taskpub.html?from=payReturn',
        ];
        if ($r['code'] == 1) {
            $this->showSuccess(__('Recharge succeeded'), request()->domain() .$jumps[$from]);
        } else {
            $this->showError(__($r['err']),request()->domain() .$jumps[$from]);
        }

    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function showSuccess($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : app('route')->buildUrl($url);
        }

        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $response = view(config('app.dispatch_success_tmpl'), $result);

        throw new \Exception($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param  mixed     $msg 提示信息
     * @param  string    $url 跳转的URL地址
     * @param  mixed     $data 返回的数据
     * @param  integer   $wait 跳转等待时间
     * @param  array     $header 发送的Header信息
     * @return void
     */
    protected function showError($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
    {
        if (is_null($url)) {
            $url = '';
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app->route->buildUrl($url);
        }

        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data,
            'url'  => $url,
            'wait' => $wait,
        ];

        $response = view(config('app.dispatch_error_tmpl'), $result);

        throw new \Exception($response);
    }

    /**
     * 支付通知
     * @return [type] [description]
     */
    public function paypalNotify()
    {
        $str = file_get_contents('php://input');
        if (!$str) {
            exit;
        }
        $instance = new Paypal;
        return $instance->notify($str);

    }

    /**
     * 提现
     */
    public function withdrawal()
    {

        Db::startTrans();
        try {
            $post         = request()->post();
            $post['u_id'] = $this->auth->u_id;
            $validate     = new \app\api\validate\UserCashRar;
            $result       = $validate->check($post);
            if (!$result) {
                return $this->error($validate->getError());
            } else {

                $cfg   = getConfig("mission");
                $model = new \app\api\model\UserCashRar;

                $post['type']  = 2;
                $post['money'] = $post['cash'] * $cfg['money_to_cash'];
                $post['follow_no']   = uniqid();

                $balance       = \app\api\model\User::find($this->auth->u_id);
                if (($balance->money - $balance->freeze) < $post['money']) {
                    throw new \Exception(__("Insufficient balance, unable to withdraw cash"), 1);
                }

                $data = $model->save($post);
                //冻结金币
                $balance->inc('freeze', $post['money'])->update();

                Db::commit();
                return $this->success(__('Operation successful'), $data);

            }
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    public function getOptions()
    {
        
 
        $params = request()->post('params');
        $params = explode(',', $params);
        foreach ($params as $key => $value) {
            if ($value == 'pay_flag') {
                $options[$value] = cashModel::getPayFlag();
            }

            if ($value == 'check_flag') {
                $options[$value] = cashModel::getCheckFlag();
            }
            if ($value == 'type') {
                $options[$value] = cashModel::getType();
            }

        }
        $data = $options;
        return $this->success(__('Operation successful'), $data);
    }
}
